package com.terra.ns.imp.common.dingtalk.notice

import com.alibaba.fastjson.JSONObject
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest
import com.aliyun.tea.TeaException
import com.aliyun.teautil.models.RuntimeOptions
import com.gzca.digit.common.dingtalk.notice.RobotSendMsgParam
import com.terra.ns.imp.common.dingtalk.client.DingtalkClient
import com.terra.ns.imp.common.dingtalk.config.DingtalkMsgProperties
import com.terra.ns.imp.common.dingtalk.notice.msgparam.MarkdownMsg
import com.terra.ns.imp.common.dingtalk.service.DingAuthService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component

/**
@author qins
@date 2023/11/15
@desc 使用机器人发送消息
 */
@Component
class RobotSendMsg {

    private val log = LoggerFactory.getLogger(this::class.java)

    @Autowired
    private lateinit var dingAuthService: DingAuthService

    @Autowired
    private lateinit var dingtalkClient: DingtalkClient

    @Autowired
    private lateinit var dingtalkMsgProperties: DingtalkMsgProperties
    /**
     * 发送消息到群聊
     */
    fun sendGroupChat(msgParam: RobotSendMsgParam) {
        val headers = OrgGroupSendHeaders()
            .setXAcsDingtalkAccessToken(dingAuthService.getAccessToken())
        val request = OrgGroupSendRequest()
            .setRobotCode(dingtalkMsgProperties.robotCode)
            .setOpenConversationId(dingtalkMsgProperties.openConversationId)
            .setMsgKey(msgParam.msgKey)
            .setMsgParam(msgParam.msgParam)
        if(!dingtalkMsgProperties.coolAppCode.isNullOrBlank()) {
            request.setCoolAppCode(dingtalkMsgProperties.coolAppCode)
        }
        try {
            val response = dingtalkClient.robotClient().orgGroupSendWithOptions(request, headers, RuntimeOptions())
        } catch (err: TeaException) {
            log.error("机器人发送群聊消息失败, 错误码：{}, 错误信息：{}", err.code, err.message, err)
            err.printStackTrace()
        }

    }

    /**
     * 发送markdown消息类型消息到群聊
     */
    @Async
    fun sendMarkdownGroupChat(msgContent: String, msgTitle: String = "错误来啦") {
        val msgParam = RobotSendMsgParam()
        msgParam.msgKey = DingMsgTypeEnum.SAMPLE_MARKDOWN.type
        val msg = MarkdownMsg()
        msg.title = msgTitle
        msg.text = msgContent
        msgParam.msgParam = JSONObject.toJSONString(msg)
        sendGroupChat(msgParam)
    }
}